# include "uces.h"

CommandResult * command_listUCEs (int argc, char *argv[]) {
	ChainingHashMap *map = getUCEsMap();
	LinkedList *a = NULL,*lst; char *tmp;
	UCE *aux;
	if (map) {
		a = lst = keySetChaining(map);
		if (lst) {
			printf("Lista de UCEs:\n");
			while (lst) {
				tmp = getData(lst);
				aux = getChaining(map,tmp);
				if (aux) printf(" %s (%d)\n",aux->name,aux->maxStudents);
				lst = lst->next;
			}
		}
	}
	if (a) freeLinkedList(a);
	else printf("Não existem UCEs registadas\n");
	return successCommandResult();
}

CommandResult * command_addUCE (int argc, char *argv[]) {
	UCE *uce;
	ChainingHashMap *map;
	LinkedList *a = NULL,*lst;
	int tem = 0;
	char *name;
	if (argc < 2) {
		printf("Argumentos: '<nome>' <max. alunos>\n");
	} else {
		map = getUCEsMap();
		if (map) {
			a = lst = keySetChaining(map);
			if (lst) {
				while (lst&&!tem) {
					name = getData(lst);
					if (!strcmp(name,argv[0])) tem = 1;
					lst = lst->next;
				}
			}
		}
		if (!tem) {
			uce = newUCE();
			uce->name = strdup(argv[0]);
			uce->maxStudents = atoi(argv[1]);
			putChaining(map,uce->name,uce);
			setProjectUnsaved();
			printf("UCE adicionada com sucesso!\n");
		} else {
			printf("UCE %s já existe\n",argv[0]);
		}
		if (a) freeLinkedList(a);
	}
	return successCommandResult();
}
CommandResult * command_removeUCE (int argc, char *argv[]) {
	ChainingHashMap *map;
	LinkedList *a=NULL,*lst;
	char *name;
	int tem = 0;
	if (argc < 1) printf("Argumentos: '<nome>'\n");
	else {
		map = getUCEsMap();
                if (map) {
                        a = lst = keySetChaining(map);
                        if (lst) {
                                while (lst&&!tem) {
                                        name = getData(lst);
                                        if (!strcmp(name,argv[0])) tem = 1;
                                        lst = lst->next;
                                }
                        }
                }
		if (a) freeLinkedList(lst);
		if (!tem) printf("UCE %s não existe\n",argv[0]);
		else {
			removeChaining(map,argv[0]);
			setProjectUnsaved();
			printf("UCE %s removida com sucesso!\n",argv[0]);
		}
	}
	return successCommandResult();
}

CommandResult * command_statusUCE (int argc, char *argv[]) {
	LinkedList *lst;
	int n = 0;
	ChainingHashMap *map = getUCEsMap();
	if (map) {
		lst = keySetChaining(map);
		if (lst) {
			n = listSize(lst);
			freeLinkedList(lst);
		}
	}
	printf("Total: %d\n",n);
	return successCommandResult();
}
